package com.example.demo.leetcode.classics150;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _65旋转链表
 * @description
 * @date 2023/07/29 9:59
 * <p>
 * ******************************************************
 */
public class _65旋转链表 {
    public ListNode rotateRight(ListNode head, int k) {
        ListNode p = head;
        int size = 0;
        while (p != null) {
            p = p.next;
            size++;
        }

        if (k == 0 || size == 0 || size == 1) {
            return head;
        }
        k = k % size;
        if (k == 0)
            return head;
        int i = size - k;
        ListNode dummy = new ListNode(-101);
        dummy.next = head;
        ListNode q = dummy;
        while (i > 0) {
            q = q.next;
            i--;
        }

        ListNode h = q.next;
        q.next = null;

        ListNode l = h;
        while (l.next != null) {
            l = l.next;
        }
        l.next = dummy.next;
        return h;


    }


    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
